package com.tucc.hello.leetcode.no1_400.no1_200.no41_60.no41;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = { 1, 1};
        System.out.println(solution.firstMissingPositive(nums));

    }

    public int firstMissingPositive(int[] nums) {
        if (nums.length == 0) {
            return 1;
        }
        if (nums.length == 1) {
            if (nums[0] != 1) {
                return 1;
            } else {
                return 2;
            }
        }
        int len = nums.length;
        for (int i = 0; i < nums.length; i++) {
            boolean flag = true;
            while(flag) {
                if (flag = nums[i] > 0 && nums[i] < len) {
                    flag = swap(nums, i, nums[i] - 1);
                }
            }
        }
        int i = 0;
        for (; i < nums.length; i++) {
            if (nums[i] != i + 1) {
                return i + 1;
            }
        }
        return nums.length + 1;
    }

    public boolean swap(int[] nums, int i, int j) {
        if (i == j || nums[i] == nums[j]) {
            return false;
        }
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
        return true;
    }

    private void printArr(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i] + ", ");
        }
        System.out.println();
    }

}
